﻿using FastReport;
using FastReport.Export.Pdf;
using FastReport.Utils;
using SMALLERP.ComClass;
using SMALLERP.DataClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XJLSC.Sy
{
    public partial class POSendMail : Form
    {
        private readonly DataBase db = new DataBase();
        private SqlDataReader sdr1;
        public delegate void Cdgzzx(object sender, EventArgs e);
        private Report FReport;
        private DataSet FDataSet;
        public String sfgx = "0";
        //定义委托对象
        public Cdgzzx cdgzzx;
        private readonly object DESencrypt;
        static SqlDependency dependency;
        private static string ConnectionString;
        private bool FReportRunning;
        public POSendMail()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strSql;
            //strSql = "SELECT TC001 采购单别,TC002 采购单号,TC003 审核日期,TC004 供应商代码,MA002 供应商名称,TC027 付款条件编号,ISNULL(NA003,'') 付款条件,TC005 币种,CAST(TC006 AS REAL) 汇率,TC031 传送次数,'' 正文内容,MA011 收件人 FROM PURTC LEFT JOIN PURMA ON TC004=MA001 LEFT JOIN CMSNA ON TC027=NA002 WHERE TC031=0 AND TC014='Y'";
            strSql = "SELECT DISTINCT '' 采购单别,PURCHASE_ORDER.DOC_NO 采购单号,CONVERT(CHAR(8),PURCHASE_ORDER.ApproveDate,112) 审核日期,SUPPLIER.SUPPLIER_CODE 供应商代码,SUPPLIER_NAME 供应商名称,ISNULL(PAYMENT_TERM.PAYMENT_TERM_CODE,'') 付款条件编号,ISNULL(PAYMENT_TERM.PAYMENT_TERM_NAME,'') 付款条件,CURRENCY.CURRENCY_NAME 币种,CAST(EXCHANGE_RATE AS REAL) 汇率,DOC_Sequence 传送次数,'' 正文内容,ISNULL(SUPPLIER_CONTACT.EMAIL,'') 收件人 FROM PURCHASE_ORDER LEFT JOIN SUPPLIER ON PURCHASE_ORDER.SUPPLIER_ID=SUPPLIER.SUPPLIER_BUSINESS_ID LEFT JOIN PAYMENT_TERM ON PAYMENT_TERM.PAYMENT_TERM_ID=PURCHASE_ORDER.PAYMENT_TERM_ID LEFT JOIN CURRENCY ON CURRENCY.CURRENCY_ID=PURCHASE_ORDER.CURRENCY_ID LEFT JOIN SUPPLIER_PURCHASE ON SUPPLIER_PURCHASE.SUPPLIER_ID=SUPPLIER.SUPPLIER_BUSINESS_ID LEFT JOIN SUPPLIER_CONTACT ON SUPPLIER_PURCHASE.SUPPLIER_BUSINESS_ID=SUPPLIER_CONTACT.SUPPLIER_BUSINESS_ID WHERE DOC_Sequence=0 AND PURCHASE_ORDER.ApproveStatus='Y'";
            try
            {
                DataTable dt;
                dt = db.GetDataSet1(strSql, "PURTD").Tables["PURTD"];
                gridControl1.DataSource = dt;
            }
            catch
            {

            }
        }

        private void POSendMail_Load(object sender, EventArgs e)
        {
            string thisFolder = Config.ApplicationFolder;
            DirectoryInfo theFolder = new DirectoryInfo(thisFolder + @"Reports\采购单\");
            FileInfo[] fileInfo = theFolder.GetFiles();
            foreach (FileInfo NextFile in fileInfo)  //遍历文件
            {
                string gsmc = "";
                //gsmc = System.IO.Path.GetFileNameWithoutExtension(theFolder + NextFile.Name);
                gsmc = System.IO.Path.GetFileNameWithoutExtension(theFolder + NextFile.Name);
                comboBox1.Items.Add(gsmc);

            }

            textBox2.Text = OperatorFile.GetIniFileString("Paragram", "From", "",
                                  Application.StartupPath + "\\Email.ini");

            textBox3.Text = ENCODE.DecryptDES(OperatorFile.GetIniFileString("Paragram", "Server", "",
                                             Application.StartupPath + "\\Email.ini"), "digiwinw");

            textBox4.Text = OperatorFile.GetIniFileString("Paragram", "PassWord", "",
                                 Application.StartupPath + "\\Email.ini");
            textBox8.Text = OperatorFile.GetIniFileString("Paragram", "qkhour", "",
                                                          Application.StartupPath + "\\Email.ini");
            textBox7.Text = OperatorFile.GetIniFileString("Paragram", "qkminute", "",
                                                       Application.StartupPath + "\\Email.ini");

            textBox21.Text = "等待中";
            textBox21.ForeColor = Color.Red;

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string strSql;
            strSql = "SELECT TC001 采购单别,TC002 采购单号,TC003 审核日期,TC004 供应商代码,MA002 供应商名称,TC027 付款条件编号,ISNULL(NA003,'') 付款条件,TC005 币种,CAST(TC006 AS REAL) 汇率,TC031 传送次数,MA011 收件人 FROM PURTC LEFT JOIN PURMA ON TC004=MA001 LEFT JOIN CMSNA ON TC027=NA002 WHERE TC031=0 AND TC014='Y' AND (MA002 LIKE '%" + textBox1.Text + "%' OR TC004='" + textBox1.Text + "') AND TC003>=CONVERT(CHAR(8),DATEADD(DAY,0,'" + dateTimePicker1.Value.ToShortDateString() + "'),112) AND TC003<=CONVERT(CHAR(8),DATEADD(DAY,0,'" + dateTimePicker2.Value.ToShortDateString() + "'),112)";
            try
            {
                DataTable dt;
                dt = db.GetDataSet1(strSql, "PURTD").Tables["PURTD"];
                gridControl2.DataSource = dt;
            }
            catch
            {

            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DesignReport();
        }

        private void DesignReport()
        {
            if (FReportRunning)
                return;
            string thisFolder = Config.ApplicationFolder;
            DirectoryInfo theFolder = new DirectoryInfo(thisFolder + @"Reports\");
            string ReportName = theFolder + "\\采购单\\" + comboBox1.Text + ".frx";
            FReport = new Report();
            FReport.Load(ReportName);
            RegisterData();
            FReport.Design();
            //PreviewReport();
        }

        private void RegisterData()
        {
            //FReport.RegisterData(FDataSet, "NorthWind");
            //FReport.RegisterData(FBusinessObject, "Categories BusinessObject");
        }

        private void PreviewReport()
        {
            if (FReportRunning)
                return;

            FReportRunning = true;
            try
            {
                RegisterData();
                FReport.Show();
            }
            finally
            {
                FReportRunning = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string strSql = "";
            int[] rows = this.gridView1.GetSelectedRows();
            foreach (int row in rows)
            {

                String gys = this.gridView1.GetRowCellValue(row, "供应商名称").ToString().Trim();
                String gysadress = this.gridView1.GetRowCellValue(row, "收件人").ToString().Trim();
                String cgdb = this.gridView1.GetRowCellValue(row, "采购单别").ToString().Trim();
                String cgdh = this.gridView1.GetRowCellValue(row, "采购单号").ToString().Trim();
                String filename = gys + "采购订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
                string savePath = string.Empty;
                savePath = "D:\\report\\" + filename;

                DataTable dt;
                FDataSet = new DataSet();
                FReport = new Report();
                FReport.Preview = preview1;
                string thisFolder = Config.ApplicationFolder;
                DirectoryInfo theFolder = new DirectoryInfo(thisFolder + @"Reports\");
                string reportName = "";
                //strSql = "select (TC018+TC019)*TC028 订金,INVMB.UDF01 型号,INVMB.UDF02 材质,INVMB.UDF60 厚,INVMB.UDF03 外径,INVMB.UDF05 内径,TC001+'-'+TC002 采购单别单号,MC002 仓库名称,*  FROM  PURTC LEFT JOIN PURTD ON TC001=TD001 AND TC002=TD002 LEFT JOIN PURMA ON MA001=TC004 LEFT JOIN INVMB ON MB001=TD004 LEFT JOIN DSCSYS.dbo.CMSMO ON MO001=MA027 LEFT JOIN CMSNJ ON NJ001=MA024 LEFT JOIN CMSNA ON NA002=MA055 LEFT JOIN CMSMC ON TD007=MC001 WHERE TC001='" + cgdb + "' AND TC002='" + cgdh + "'"; //易飞
                strSql = "select 0 订金,INVMB.UDF01 型号,INVMB.UDF02 材质,'' 厚,'' 外径,'' 内径,TC001+'-'+TC002 采购单别单号,MC002 仓库名称,*  FROM  PURTC LEFT JOIN PURTD ON TC001=TD001 AND TC002=TD002 LEFT JOIN PURMA ON MA001=TC004 LEFT JOIN INVMB ON MB001=TD004  LEFT JOIN CMSMC ON TD007=MC001 WHERE RTRIM(TC001)+'-'+RTRIM(TC002) =RTRIM('" + cgdh + "')";  //E10
                FDataSet = db.GetDataSet1(strSql, "Table");
                dt = db.GetDataSet1(strSql, "PURTD").Tables["PURTD"];
                reportName = theFolder + comboBox1.Text.Trim() + ".frx";
                preview1.Location = new Point(0, 0);
                FReport.Load(reportName);
                FReport.RegisterData(FDataSet);
                FReport.Prepare();
                //导出PDF报表
                PDFExport export = new PDFExport();
                FReport.Export(export, savePath);
                FReport.Dispose();

                try
                {
                    Thread.Sleep(5000); //暂停5秒再开始发邮件
                    SendMailcgd(filename, gys, gysadress,cgdh);
                }
                catch
                {

                }
            }
        }

        public void SendMailcgd(String filename, String gys, String gysadress, String cgdh)
        {
            String strSql = "";
            DataBase db = new DataBase();
            DateTime dt = DateTime.Now;
            DateTime dt1 = dt.AddDays(-1);
            string zr = dt1.ToShortDateString();
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(gysadress);

            //for (int i = 0; i <= dataGridView4.Rows.Count - 1; i++)
            //{
            //    string sjr = (dataGridView4.Rows[i].Cells["EmailAdressA"].Value == null) ? "" : dataGridView4.Rows[i].Cells["EmailAdressA"].Value.ToString();
            //    if (sjr != "")
            //    {
            //        msg.To.Add(dataGridView4.Rows[i].Cells["EmailAdressA"].Value.ToString());
            //    }
            //}
            //msg.To.Add(textBox4.Text);
            /*   
             msg.To.Add("b@b.com");   
            * msg.To.Add("b@b.com");   
            * msg.To.Add("b@b.com");可以发送给多人   
            */
            // msg.CC.Add("2670828470@qq.com");
            /*   
            * msg.CC.Add("c@c.com");   
            * msg.CC.Add("c@c.com");可以抄送给多人   
            */
            msg.From = new MailAddress(textBox2.Text, "阿波罗供应链管理系统", System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
            msg.Subject = zr + "采购订单";//邮件标题    
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码    
            msg.Body = gys + "：\r\n    附件为" + zr + "采购订单,请及时审核，如有异议，请及时提出！";//邮件内容    
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码    
            msg.IsBodyHtml = false;//是否是HTML邮件    
            msg.Priority = MailPriority.High;//邮件优先级    

            //以下添加附件
            string sfile = "D:\\report\\" + filename;//添加附件
            msg.Attachments.Add(new Attachment(sfile));

            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential(textBox2.Text, textBox4.Text);
            //见下图1
            //上述写你的QQ邮箱和密码    
            client.Port = 587;//QQ邮箱使用的端口    
            client.Host = textBox3.Text;
            client.EnableSsl = true;//经过ssl加密    
            object userState = msg;
            string dosomesting = sfile;
            try
            {
                client.SendAsync(msg, userState);
                strSql = "UPDATE PURCHASE_ORDER SET DOC_Sequence=DOC_Sequence+1 WHERE DOC_NO='" + cgdh + "'";
                try
                {
                    if (db.ExecDataBySql1(strSql) > 0)
                    {
                    }
                    else
                    {
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "软件提示");
                    throw ex;
                }
                //成功
                Writelog($"{dosomesting}发送成功");
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                //错误
                Writelog($"{dosomesting}发送失败");
            }
        }


        static void Writelog(string logContent)
        {
            StreamWriter stream;
            //写入日志内容
            string path = AppDomain.CurrentDomain.BaseDirectory + "//logs";
            //检查物理路径是否存在，不存在则创建路径
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            stream = new StreamWriter(path + $"\\log{DateTime.Now.ToString("yyyyMMdd")}.txt", true, Encoding.Default);
            stream.Write(DateTime.Now.ToString() + ":" + logContent);
            stream.Write("\r\n");//追加写入
            stream.Flush();
            stream.Close();//一定要关闭流
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.CheckState==CheckState.Checked)
            {
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Enabled = true;
                timer.Interval = 60000;//60秒执行间隔时间,单位为毫秒    
                timer.Start();
                timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer5_Elapsed);
                textBox21.Text = "运行中";
                textBox21.ForeColor = Color.Green;
            }
            else
            {
                textBox21.Text = "等待中";
                textBox21.ForeColor = Color.Red;
            }
        }

        private void Timer5_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            int hour = Convert.ToInt16(textBox8.Text);
            int minutes = Convert.ToInt16(textBox7.Text);
            // 得到intHour,intMinute,intSecond，是当前系统时间    
            int intHour = e.SignalTime.Hour;
            int intMinute = e.SignalTime.Minute;
            int intSecond = e.SignalTime.Second;
            // System.Windows.Forms.MessageBox.Show(intSecond.ToString());
            //自己设置hour,minuter,second,到设定的时间就开始执行程序    
            if (intHour == hour && intMinute == minutes & textBox21.Text == "运行中")
            {
                string strSql = "";
                //先查询需要推送的采购单信息
                //strSql = "SELECT TC001 采购单别,TC002 采购单号,TC003 审核日期,TC004 供应商代码,MA002 供应商名称,TC027 付款条件编号,ISNULL(NA003,'') 付款条件,TC005 币种,CAST(TC006 AS REAL) 汇率,TC031 传送次数,'' 正文内容,MA011 收件人 FROM PURTC LEFT JOIN PURMA ON TC004=MA001 LEFT JOIN CMSNA ON TC027=NA002 WHERE TC031=0 AND TC014='Y'";
                strSql = "SELECT DISTINCT '' 采购单别,PURCHASE_ORDER.DOC_NO 采购单号,CONVERT(CHAR(8),PURCHASE_ORDER.ApproveDate,112) 审核日期,SUPPLIER.SUPPLIER_CODE 供应商代码,SUPPLIER_NAME 供应商名称,ISNULL(PAYMENT_TERM.PAYMENT_TERM_CODE,'') 付款条件编号,ISNULL(PAYMENT_TERM.PAYMENT_TERM_NAME,'') 付款条件,CURRENCY.CURRENCY_NAME 币种,CAST(EXCHANGE_RATE AS REAL) 汇率,DOC_Sequence 传送次数,'' 正文内容,ISNULL(SUPPLIER_CONTACT.EMAIL,'') 收件人 FROM PURCHASE_ORDER LEFT JOIN SUPPLIER ON PURCHASE_ORDER.SUPPLIER_ID=SUPPLIER.SUPPLIER_BUSINESS_ID LEFT JOIN PAYMENT_TERM ON PAYMENT_TERM.PAYMENT_TERM_ID=PURCHASE_ORDER.PAYMENT_TERM_ID LEFT JOIN CURRENCY ON CURRENCY.CURRENCY_ID=PURCHASE_ORDER.CURRENCY_ID LEFT JOIN SUPPLIER_PURCHASE ON SUPPLIER_PURCHASE.SUPPLIER_ID=SUPPLIER.SUPPLIER_BUSINESS_ID LEFT JOIN SUPPLIER_CONTACT ON SUPPLIER_PURCHASE.SUPPLIER_BUSINESS_ID=SUPPLIER_CONTACT.SUPPLIER_BUSINESS_ID WHERE DOC_Sequence=0 AND PURCHASE_ORDER.ApproveStatus='Y'";
                try
                {
                    DataTable dt;
                    dt = db.GetDataSet1(strSql, "PURTD").Tables["PURTD"];
                    gridControl1.DataSource = dt;
                }
                catch
                {

                }
                //然后逐家发送
                for (int i=0;i<=gridView1.RowCount-1;i++)
                {

                    String gys = this.gridView1.GetRowCellValue(i, "供应商名称").ToString().Trim();
                    String gysadress = this.gridView1.GetRowCellValue(i, "收件人").ToString().Trim();
                    String cgdb = this.gridView1.GetRowCellValue(i, "采购单别").ToString().Trim();
                    String cgdh = this.gridView1.GetRowCellValue(i, "采购单号").ToString().Trim();
                    String filename = gys + "采购订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
                    string savePath = string.Empty;
                    savePath = "D:\\report\\" + filename;
                    DataTable dt;
                    FDataSet = new DataSet();
                    FReport = new Report();
                    FReport.Preview = preview1;
                    string thisFolder = Config.ApplicationFolder;
                    DirectoryInfo theFolder = new DirectoryInfo(thisFolder + @"Reports\");
                    string reportName = "";
                    //strSql = "select (TC018+TC019)*TC028 订金,INVMB.UDF01 型号,INVMB.UDF02 材质,INVMB.UDF60 厚,INVMB.UDF03 外径,INVMB.UDF05 内径,TC001+'-'+TC002 采购单别单号,MC002 仓库名称,*  FROM  PURTC LEFT JOIN PURTD ON TC001=TD001 AND TC002=TD002 LEFT JOIN PURMA ON MA001=TC004 LEFT JOIN INVMB ON MB001=TD004 LEFT JOIN DSCSYS.dbo.CMSMO ON MO001=MA027 LEFT JOIN CMSNJ ON NJ001=MA024 LEFT JOIN CMSNA ON NA002=MA055 LEFT JOIN CMSMC ON TD007=MC001 WHERE TC001='" + cgdb + "' AND TC002='" + cgdh + "'"; //易飞
                    strSql = "select 0 订金,INVMB.UDF01 型号,INVMB.UDF02 材质,'' 厚,'' 外径,'' 内径,TC001+'-'+TC002 采购单别单号,MC002 仓库名称,*  FROM  PURTC LEFT JOIN PURTD ON TC001=TD001 AND TC002=TD002 LEFT JOIN PURMA ON MA001=TC004 LEFT JOIN INVMB ON MB001=TD004  LEFT JOIN CMSMC ON TD007=MC001 WHERE RTRIM(TC001)+'-'+RTRIM(TC002) =RTRIM('" + cgdh + "')";  //E10
                    FDataSet = db.GetDataSet1(strSql, "Table");
                    dt = db.GetDataSet1(strSql, "PURTD").Tables["PURTD"];
                    reportName = theFolder + comboBox1.Text.Trim() + ".frx";
                    preview1.Location = new Point(0, 0);
                    FReport.Load(reportName);
                    FReport.RegisterData(FDataSet);
                    FReport.Prepare();
                    //导出PDF报表
                    PDFExport export = new PDFExport();
                    FReport.Export(export, savePath);
                    FReport.Dispose();

                    try
                    {
                        Thread.Sleep(5000); //暂停5秒再开始发邮件
                        SendMailcgd(filename, gys, gysadress,cgdh);
                    }
                    catch
                    {

                    }
                }
            }

        }
    }
}
